package com.ruoyi.ghxx.controller;

import cn.hutool.core.util.NumberUtil;
import com.alibaba.fastjson2.JSON;
import com.github.pagehelper.PageHelper;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.page.TableSupport;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.utils.sql.SqlUtil;
import com.ruoyi.ghxx.aop.SysInitData;
import com.ruoyi.ghxx.domain.SysUpload;
import com.ruoyi.ghxx.modelVo.BImageType;
import com.ruoyi.ghxx.service.ISysUploadService;
import com.ruoyi.ghxx.util.Detect;
import com.ruoyi.ghxx.util.ImageWatermarkUtils;
import com.ruoyi.system.service.ISysDictTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.*;
import java.util.List;

/**
 * 上传信息Controller
 * 
 * @author ruoyi
 * @date 2020-11-17
 */
@RestController
@RequestMapping("/ghxx/upload")
public class SysUploadController extends BaseController
{
    @Autowired
    private ISysUploadService sysUploadService;
    @Value("${ruoyi.filepath}")
    private String filepath;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private ISysDictTypeService dictTypeService;
    @Autowired
    private RedisCache redisCache;
    /**
     * 查询上传信息列表
     */
//    @PreAuthorize("@ss.hasPermi('ghxx:upload:list')")
    @GetMapping("/list")
    //@SysQueryData
    public TableDataInfo list(SysUpload sysUpload)
    {
        startPage();
        Boolean isAuth=false;
        if("我的收藏".equals(sysUpload.getModuleName())){
            sysUpload.setUpdateBy(SecurityUtils.getUsername());
            isAuth=true;
        }
        for (int i = 0; i <SecurityUtils.getLoginUser().getUser().getRoles().size() ; i++) {
            SysRole sysRole = SecurityUtils.getLoginUser().getUser().getRoles().get(i);
            if(sysRole.getRoleKey().equals("gallery_user")){
                isAuth=true;
            }
        }
        if(!("admin".equals(SecurityUtils.getUsername())||isAuth)){
            PageDomain pageDomain = TableSupport.buildPageRequest();
            Integer pageNum = pageDomain.getPageNum();
            Integer pageSize = pageDomain.getPageSize();
            pageNum=1;
            pageSize=10;
            if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize))
            {
                String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());
                PageHelper.startPage(pageNum, pageSize, orderBy);
            }
        }
        List<SysUpload> list = sysUploadService.selectSysUploadList(sysUpload);
        return getDataTable(list);
    }

    /**
     * 导出上传信息列表
     */
//    @PreAuthorize("@ss.hasPermi('ghxx:upload:export')")
    @Log(title = "上传信息", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(SysUpload sysUpload)
    {
        List<SysUpload> list = sysUploadService.selectSysUploadList(sysUpload);
        ExcelUtil<SysUpload> util = new ExcelUtil<SysUpload>(SysUpload.class);
        return util.exportExcel(list, "upload");
    }

    /**
     * 获取上传信息详细信息
     */
//    @PreAuthorize("@ss.hasPermi('ghxx:upload:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(sysUploadService.selectSysUploadById(id));
    }

    /**
     * 新增上传信息
     */
//    @PreAuthorize("@ss.hasPermi('ghxx:upload:add')")
    @Log(title = "上传信息", businessType = BusinessType.INSERT)
    @PostMapping
    @SysInitData
    public AjaxResult add(@RequestBody SysUpload sysUpload)
    {
        return toAjax(sysUploadService.insertSysUpload(sysUpload));
    }

    /**
     * 修改上传信息
     */
//    @PreAuthorize("@ss.hasPermi('ghxx:upload:edit')")
    @Log(title = "上传信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SysUpload sysUpload)
    {
        return toAjax(sysUploadService.updateSysUpload(sysUpload));
    }

    /**
     * 删除上传信息
     */
//    @PreAuthorize("@ss.hasPermi('ghxx:upload:remove')")
    @Log(title = "上传信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(sysUploadService.deleteSysUploadByIds(ids));
    }

    /**
     * 上传组件
     */
    @Log(title = "上传组件", businessType = BusinessType.IMPORT)
//    @PreAuthorize("@ss.hasPermi('ghxx:upload:uploadData')")
    @PostMapping("/uploadData")
    public AjaxResult importData(MultipartFile file, String moduleName, String moduleGuid , Boolean isMultiple) throws Exception
    {
        if(isMultiple==null){
            //判断图片是否多条上传
            isMultiple=false;
        }
        if (!file.isEmpty())
        {
            MultipartFile multipartFile = ImageWatermarkUtils.markWithContent(file, "CL@qq_799807906");
            String uploadPath="";
            try{
                uploadPath = FileUploadUtils.upload(RuoYiConfig.getUploadPath(), multipartFile);
            }catch (Exception e){
                return AjaxResult.error(500,"上传组件异常，"+e.toString());
            }
            LoginUser loginUser = SecurityUtils.getLoginUser();
            SysUpload sysUpload =new SysUpload();
            if(Detect.notNull(loginUser.getUser().getDeptId())){
                String deptIds=","+loginUser.getUser().getDept().getAncestors()+","+loginUser.getUser().getDeptId()+",";
                sysUpload.setDeptIdStrs(deptIds);
            }
            String fileName=file.getOriginalFilename();
            if("云组态".equals(moduleGuid)&&fileName.length()>10){
                fileName=moduleName;
            }
            sysUpload.setFileName(fileName);
            sysUpload.setModuleName(moduleName);
            sysUpload.setUpdateBy(loginUser.getUsername());
            sysUpload.setUpdateTime(new Date());
            sysUpload.setResourceUrl(uploadPath);
            sysUpload.setModuleGuid(moduleGuid);
            if(Detect.notEmpty(sysUpload.getModuleGuid())&&isMultiple==false){
                SysUpload sysUploadQuery =new SysUpload();
                sysUploadQuery.setModuleGuid(moduleGuid);
                sysUploadQuery.setModuleName(moduleName);
                List<SysUpload> sysUploads = sysUploadService.selectSysUploadList(sysUploadQuery);
                if(sysUploads.size()>0){
                    sysUpload.setId(sysUploads.get(0).getId());
                    sysUploadService.updateSysUpload(sysUpload);
                    if(Detect.notEmpty(sysUploads.get(0).getResourceUrl())){
                        String newUrl = sysUploads.get(0).getResourceUrl().replace("/profile", "").replace("/avatar", "");
                        File fileQuery=new File(RuoYiConfig.getAvatarPath()+newUrl);
                        if(fileQuery.exists()){
                            System.out.println("删除之前的图片资源");
                            fileQuery.delete();
                        }
                    }
                }else{
                    sysUploadService.insertSysUpload(sysUpload);
                }
            }else{
                sysUploadService.insertSysUpload(sysUpload);
            }
            return AjaxResult.success("上传组件成功");
        }
        return AjaxResult.error(500,"上传组件异常，请联系管理员");
    }
    /**
     * 版本升级
     */
    @Log(title = "版本升级", businessType = BusinessType.IMPORT)
//    @PreAuthorize("@ss.hasPermi('ghxx:upload:uploadData')")
    @PostMapping("/versionUpgrade")
    public AjaxResult versionUpgrade(MultipartFile file, String moduleName) throws Exception
    {
        if (!file.isEmpty())
        {
            String avatar="";
            try{
                avatar = FileUploadUtils.upload(RuoYiConfig.getAvatarPath(), file);
            }catch (Exception e){
                return AjaxResult.error(500,"上传组件异常，"+e.toString());
            }
            LoginUser loginUser = SecurityUtils.getLoginUser();
            SysUpload sysUpload =new SysUpload();
            if(Detect.notNull(loginUser.getUser().getDeptId())){
                String deptIds=","+loginUser.getUser().getDept().getAncestors()+","+loginUser.getUser().getDeptId()+",";
                sysUpload.setDeptIdStrs(deptIds);
            }
            sysUpload.setFileName(file.getOriginalFilename());
            sysUpload.setModuleName(moduleName);
            sysUpload.setUpdateBy(loginUser.getUsername());
            sysUpload.setUpdateTime(new Date());
            sysUpload.setResourceUrl(avatar);
            String sql="select * from sys_upload where module_name='物联云APP' order by id desc limit 1";
            BeanPropertyRowMapper<SysUpload> sysUploadBeanPropertyRowMapper = new BeanPropertyRowMapper<>(SysUpload.class);
            List<SysUpload> sysUploads = jdbcTemplate.query(sql, sysUploadBeanPropertyRowMapper);
            if(sysUploads.size()>0){
                SysUpload sysUploadQuery = sysUploads.get(0);
                sysUpload.setVersionCode(sysUploadQuery.getVersionCode()+1);
                double newVersionName = Convert.toDouble(sysUploadQuery.getVersionName()) + 0.1;
                sysUpload.setVersionName(NumberUtil.round(newVersionName,1)+"");
            }else{
                sysUpload.setVersionCode(1);
                sysUpload.setVersionName("1.1");
            }

            sysUploadService.insertSysUpload(sysUpload);
            return AjaxResult.success("上传组件成功");
        }
        return AjaxResult.error(500,"上传组件异常，请联系管理员");
    }
    /**
     * 获取app
     */

    @GetMapping("/getApp")
    public AjaxResult getApp() throws Exception
    {
        String sql="select * from sys_upload where module_name='物联云APP' order by id desc limit 1";
        BeanPropertyRowMapper<SysUpload> sysUploadBeanPropertyRowMapper = new BeanPropertyRowMapper<>(SysUpload.class);
        List<SysUpload> sysUploads = jdbcTemplate.query(sql, sysUploadBeanPropertyRowMapper);
        if(sysUploads.size()>0){
            SysUpload sysUploadQuery = sysUploads.get(0);
            return AjaxResult.success("版本更新成功",sysUploadQuery);
        }else{
            return AjaxResult.error(500,"无更新版本");
        }
    }
    /**/
    @GetMapping("/getImageType")
    public AjaxResult getImageType() throws Exception{
        List<Object> sysImageTypeObj = redisCache.getCacheList("sys_image_type");
        List<BImageType> typeArrayListCache=StringUtils.cast(sysImageTypeObj);
        if (StringUtils.isNotEmpty(typeArrayListCache)){
            return AjaxResult.success(typeArrayListCache);
        }else {
            List<SysDictData> sysDictDataList = dictTypeService.selectDictDataByType("sys_image_type");
            List<BImageType> typeArrayList=new ArrayList<>();
            for (int i = 0; i < sysDictDataList.size(); i++) {
                SysDictData sysDictData = JSON.parseObject(JSON.toJSONString(sysDictDataList.get(i)), SysDictData.class);
                String lable=sysDictData.getDictLabel();
                String sql="select count(1) from sys_upload where module_guid=? and module_name=?";
                BImageType bImageType=new BImageType();
                bImageType.setId(1000+(i+1)+"-"+ sysDictData.getDictValue());
                bImageType.setTitle(lable);
                bImageType.setNumber(jdbcTemplate.queryForObject(sql, Long.class, "云组态", sysDictData.getDictValue()));
                typeArrayList.add(bImageType);
            }
            redisCache.setCacheList("sys_image_type",typeArrayList);
            return AjaxResult.success(typeArrayList);
        }
    }
}
